package net.stuffrepos.userdesktopdatabase.helper;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import net.stuffrepos.userdesktopdatabase.Database;
import net.stuffrepos.userdesktopdatabase.Migration;
import net.stuffrepos.util.config.UserConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class DatabaseManager {

    private static final Log log = LogFactory.getLog(DatabaseManager.class);
    private final UserConfig userConfig;
    private final Migration[] migrations;
    private final Set<Class> hibernateEntities;
    private HibernateHelper hibernate;
    private boolean clearDatabase = false;
    private Database database;

    public DatabaseManager(UserConfig userConfig, Migration[] migrations, Class[] hibernateEntities) {
        this.userConfig = userConfig;
        this.migrations = migrations;
        this.hibernateEntities = new HashSet<Class>(Arrays.asList(hibernateEntities));
    }

    public HibernateHelper getHibernate() {
        return hibernate;
    }

    public void requestDatabase(int version) {
        try {
            log.trace("Version: " + version);
            setDatabase(null, clearDatabase, version);
            database.open(version);
        } catch (SQLException ex) {
            log.fatal("Exception at opening database", ex);
            System.exit(0);
        }
    }

    public void setDatabase(String database) {
        setDatabase(database, false);
    }

    public void setDatabase(String database, boolean clearDatabase) {
        setDatabase(database, clearDatabase, Database.LAST_VERSION);
    }

    public void setDatabase(String aDatabase, boolean clearDatabase, int version) {
        closeDatabase();

        try {
            database = new Database(userConfig, migrations, aDatabase);
            if (clearDatabase) {
                database.clearDatabase();
            }
            database.open(version);
            hibernate = new HibernateHelper(
                    database.getConnectionUrl(),
                    hibernateEntities
            );
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    public void closeDatabase() {
        if (hibernate != null) {
            hibernate.close();
        }
        if (database != null) {
            database.close();
        }
    }

    public void setClearDatabase(boolean clearDatabase) {
        this.clearDatabase = clearDatabase;
    }

    public String getConnectionUrl() {
        return database.getConnectionUrl();
    }
}
